<template>
  <n-tabs type="segment" style="height: 100%">
    <n-tab-pane style="height: 100%" name="basic" tab="基础配置">
      <div class="tab-wrapper" v-if="feature">
        <div class="top">
          <SettingItem name="点位名称">
            <n-input
              size="small"
              v-model:value="feature.name"
              placeholder="请输入点位名称"
            ></n-input>
          </SettingItem>
          <SettingItem name="UUID">
            <n-input
              size="small"
              placeholder="请输入UUID"
              v-model:value="feature.pid"
            ></n-input>
          </SettingItem>
          <!-- <SettingItem name="中心坐标">
            <div class="flex">
              <n-input
                pair
                separator="-"
                :placeholder="['经度', '纬度']"
                clearable
                size="small"
                v-model:value="feature.geometry.coordinates"
              />
            </div>
          </SettingItem> -->

          <SettingItem name="创建者">
            <div class="user">
              <n-avatar
                size="small"
                :src="'https://rcs-bucket.oss-cn-hangzhou.aliyuncs.com/app%2Fspace%2F7c7adc8ccc524163921d2d403f1f3c5b_d7f6b05214f24a6a842f2acaa2e30146_buoumao-zhongdianse.png'"
              >
              </n-avatar>
              <span>{{ "管理员" }}</span>
            </div>
          </SettingItem>

          <!-- <SettingItem name="发布状态">
              <div style="display: flex">
                <n-select
                  size="small"
                  v-model:value="feature.status"
                  :options="featureStatus"
                ></n-select>
              </div>
            </SettingItem> -->
          <SettingItem name="是否显示">
            <div style="display: flex">
              <n-switch
                v-model:value="feature.status"
                size="large"
                :round="false"
                :checked-value="1"
                :unchecked-value="0"
              />
            </div>
          </SettingItem>
          <SettingItem name="创建日期">
            <TimePopover :value="feature.createTime">
              <div class="inline-item">{{ feature.createTime }}</div>
            </TimePopover>
          </SettingItem>
          <SettingItem name="更新日期">
            <TimePopover :value="feature.updateTime">
              <div class="inline-item">{{ feature.updateTime }}</div>
            </TimePopover>
          </SettingItem>
          <!-- <SettingCollapse name="点位日期">
            
          </SettingCollapse> -->
          <SettingCollapse name="坐标配置">
            <template #header-extra>
              <n-button
                @click="handleEdit"
                v-if="!mapStore.editMode"
                size="small"
                strong
                secondary
                type="primary"
                >从地图上修改</n-button
              >
              <n-space v-else>
                <n-button
                  size="small"
                  @click="handleEditComplete"
                  type="primary"
                  secondary
                  strong
                >
                  保存</n-button
                >
                <n-button
                  size="small"
                  @click="handleEditCancel"
                  type="error"
                  secondary
                  strong
                >
                  取消</n-button
                >
              </n-space>
            </template>
            <div v-if="feature.geometry.type == 'Point'" vertical>
              <SettingItem name="坐标">
                <div class="flex">
                  <n-input
                    pair
                    separator="-"
                    :placeholder="['经度', '纬度']"
                    clearable
                    size="small"
                    v-model:value="feature.geometry.coordinates"
                  />
                </div>
                <!-- <n-input size="small" placeholder="请输入点位名称"></n-input> -->
              </SettingItem>
            </div>
            <div v-if="feature.geometry.type == 'Polygon'" vertical>
              <SettingItem
                v-for="(item, index) in feature.geometry.coordinates[0]"
                :name="`坐标-${index}`"
              >
                <div class="flex">
                  <n-input
                    pair
                    separator="-"
                    :placeholder="['经度', '纬度']"
                    clearable
                    size="small"
                    v-model:value="feature.geometry.coordinates[0][index]"
                  />
                </div>
                <!-- <n-input size="small" placeholder="请输入点位名称"></n-input> -->
              </SettingItem>
            </div>
            <div v-else-if="feature.geometry.type == 'LineString'" vertical>
              <SettingItem
                v-for="(item, index) in feature.geometry.coordinates"
                :name="`坐标-${index}`"
              >
                <div class="flex">
                  <n-input
                    pair
                    separator="-"
                    :placeholder="['经度', '纬度']"
                    clearable
                    size="small"
                    v-model:value="feature.geometry.coordinates[index]"
                  />
                </div>
                <!-- <n-input size="small" placeholder="请输入点位名称"></n-input> -->
              </SettingItem>
            </div>
          </SettingCollapse>
        </div>
        <div class="bottom">
          <n-button @click="handleConfirm" class="bottom-button" type="success"
            >保存</n-button
          >
          <n-button @click="handleDelete" class="bottom-button" type="error"
            >删除</n-button
          >
        </div>
      </div>
      <div v-else>-- 请选择点位 --</div>
    </n-tab-pane>
    <n-tab-pane name="data" tab="数据配置" style="height: 100%">
      <div class="tab-wrapper" v-if="feature">
        <div class="top">
          <SettingItem
            v-for="item in layer.columns"
            :key="feature.pid + item.key"
            :name="item.name"
          >
            <n-input
              v-if="item.type == 'text'"
              size="small"
              v-model:value="feature.properties[item.key]"
              :placeholder="`请输入${item.name}`"
            ></n-input>
            <n-input-number
              v-else-if="item.type == 'number'"
              size="small"
              v-model:value="feature.properties[item.key]"
              :placeholder="`请输入${item.name}`"
            ></n-input-number>
            <n-select
              v-else-if="item.type == 'select'"
              size="small"
              :options="
                item.options.map((item) => {
                  return { label: item.key, value: item.value };
                })
              "
              v-model:value="feature.properties[item.key]"
              :placeholder="`请选择${item.name}`"
            ></n-select>
            <n-upload
              v-else-if="item.type == 'image'"
              size="small"
              directory-dnd
              :max="1"
              v-model:value="feature.properties[item.key]"
              :placeholder="`请选择${item.name}`"
              :show-file-list="false"
              @before-upload="handleImageBeforeUpload($event, item.key)"
            >
              <n-upload-dragger v-if="!feature.properties[item.key]">
                <n-text style="font-size: 12px"> 点击或者拖动文件 </n-text>
              </n-upload-dragger>
              <img
                class="image-wrapper"
                v-else
                :src="feature.properties[item.key]"
                alt=""
              />
            </n-upload>
          </SettingItem>
        </div>
        <div class="bottom">
          <n-button @click="handleConfirm" class="bottom-button" type="success"
            >保存</n-button
          >
          <n-button @click="handleDelete" class="bottom-button" type="error"
            >删除</n-button
          >
        </div>
      </div>
    </n-tab-pane>
    <n-tab-pane name="advance" tab="高级配置"> --暂无-- </n-tab-pane>
  </n-tabs>
</template>

<script lang="ts" setup>
import SettingItem from "./components/item.vue";
import SettingCollapse from "./components/collapse.vue";
import { LocationOutline } from "@vicons/ionicons5";
import { useMapStore } from "@/store/map";
import { computed, watch, ref } from "vue";
import { useDialog, useMessage } from "naive-ui";
import TimePopover from "@/components/time-popover/index.vue";
import { useEventBus } from "@vueuse/core";
import { deleteFeature, updateFeature, uploadFile } from "@/api";
import WKT from "terraformer-wkt-parser";
const dialog = useDialog();
const mapBus = useEventBus("map");
const featureConfigBus = useEventBus("feature.config");
const message = useMessage();
const mapStore = useMapStore();
const layer = computed(() =>
  mapStore.datasetInfo.layers.find((item) => item.pid == mapStore.selectLayer)
);
// const feature = ref();
const featureStatus = [
  {
    label: "未发布",
    value: 0,
  },
  {
    label: "待审核",
    value: 1,
  },
  {
    label: "已发布",
    value: 2,
  },
  {
    label: "已禁用",
    value: 3,
  },
];
const handleDelete = () => {
  dialog.error({
    title: "警告",
    content: "删除后数据不可逆，请确认",
    positiveText: "确定删除",
    negativeText: "取消",
    onPositiveClick: () => {
      deleteFeature(feature.value.id)
        .then((res) => {
          message.success("删除成功");
          const layer = mapStore.getCurrentLayer();
          layer.features = layer.features.filter(
            (item) => item.id !== feature.value.id
          );
          mapBus.emit({
            type: "render.layer",
            value: layer,
          });
        })
        .catch((e) => {
          message.error("删除失败");
        });

      // message.success('确定')
    },
    onNegativeClick: () => {
      // message.error('不确定')
    },
  });
};
const handleConfirm = () => {
  console.log(feature.value);
  const data = JSON.parse(JSON.stringify(feature.value));
  // data.center = WKT.convert(data.center);
  // data.geometry = WKT.convert(data.geometry);
  updateFeature(data)
    .then((res) => {
      console.log(res);
      message.success("保存成功");
    })
    .catch((e) => {
      console.log(e);
      message.error("保存失败");
    });
};
const handleEdit = () => {
  mapStore.editMode = true;
  mapBus.emit({
    type: "edit",
    value: feature.value.geometry,
    pid: feature.value.pid,
  });
};
const handleEditComplete = () => {
  mapStore.editMode = false;
  mapBus.emit({
    type: "edit.save",
  });
};
const handleEditCancel = () => {
  dialog.error({
    title: "取消编辑",
    content: "取消后将失去所有修改记录",
    positiveText: "确定",
    onPositiveClick: () => {
      mapStore.editMode = false;
      mapBus.emit({
        type: "edit.cancel",
      });
    },
  });
  // mapStore.editMode = false;
  // Message;
};
const handleMapEvent = (e: any) => {
  if (e.type == "result") {
    const layer = mapStore.datasetInfo.layers.find(
      (item) => item.pid == mapStore.selectLayer
    );
    // if (feature.value.geometry.type == "Point") {
    //   feature.value.center = feature.value.geometry;
    // }
    feature.value.geometry = e.value.geometry;
    mapBus.emit({
      type: "render.layer",
      value: layer,
    });
    // mapBus.emit({
    //   type: "render",
    //   value: layer.features,
    // });
    console.log(layer.features);
    // mapStore.getFeaturesByPid(mapStore.selectLayer);
    // console.log(feature.value);
  }
};
const feature = computed(() => {
  const layer = mapStore.datasetInfo.layers.find(
    (item) => item.pid == mapStore.selectLayer
  );
  console.log("select feature", layer, mapStore.selectFeature);
  if (layer) {
    return layer.features.find((item) => item.id == mapStore.selectFeature);
  } else {
    return null;
  }
});
// watch(
//   () => mapStore.selectFeature,
//   (val) => {
//     // console.log("mapStore.layers", mapStore.layers);
//     const layer = mapStore.datasetInfo.layers.find(
//       (item) => item.pid == mapStore.selectLayer
//     );
//     // console.log(layer);
//     if (layer) {
//       feature.value = layer.features.find(
//         (item) => item.pid == mapStore.selectFeature
//       );
//       console.log(feature.value);
//     } else {
//       feature.value = null;
//     }
//   },
//   {
//     immediate: true,
//   }
// );
featureConfigBus.on(handleMapEvent);
const handleImageBeforeUpload = (e, key) => {
  console.log(e);
  const formData = new FormData();
  formData.append("file", e.file.file);
  uploadFile(formData).then((res: any) => {
    console.log(res.data.url, key);
    setTimeout(() => {
      feature.value.properties[key] = "https://" + res.data.url;
    }, 100);
  });
  return false;
};
// mapBus.on()
</script>

<style lang="scss" scoped>
.flex {
  display: flex;
  align-items: center;
}
.user {
  display: flex;
  align-items: center;
  cursor: pointer;
  span {
    margin-right: 6px;
  }
}
.tab-wrapper {
  height: 100%;
  display: flex;
  flex-direction: column;
  .top {
    flex: 1;
  }
  .bottom-button {
    width: 100%;
    margin-top: 10px;
  }
  .inline-item {
    height: 28px;
    line-height: 28px;
    text-align: left;
  }
}
.image-wrapper {
  width: 200px;
  max-height: 100px;
  object-fit: contain;
  background-color: rgba(255, 255, 255, 0.1);
  padding: 6px;
  border-radius: 4px;
}
</style>
